package es.qplayas;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.prasanta.json.JSONHandler;

import es.qplayas.core.Caracteristicas;
import es.qplayas.core.Playa;
import es.qplayas.core.Posicion;

public class BeachParser {
	
	public BeachParser(){
		
	}
	
	public List<Playa> parse(JSONObject json){
		JSONArray jsonArray = null;
		try {
			jsonArray = json.getJSONArray("results");
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		List<Playa> playas = new ArrayList<Playa>();
		for(int i=0;i<jsonArray.length();i++){
			Playa playa = null;
			try {
				String element = jsonArray.getString(i);
				playa = (Playa)(new JSONHandler().parse(element, Playa.class, "es.qplayas.core"));
				playa.setId(i);
				JSONObject jsonTmp = new JSONObject(element);
				Posicion posicion = (Posicion)(new JSONHandler().parse(jsonTmp.getString("posicion"), Posicion.class, "es.qplayas.core"));
				playa.setPosicion(posicion);
				Caracteristicas caracteristicas = (Caracteristicas)(new JSONHandler().parse(jsonTmp.getString("caracteristicas"), Caracteristicas.class, "es.qplayas.core"));
				playa.setCaracteristicas(caracteristicas);
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			playas.add(playa);
		}
		return playas;
	}

}
